package com.hthy.futures.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hthy.futures.AppContext;
import com.hthy.futures.R;
import com.hthy.futures.api.ST_TradeApi;
import com.hthy.futures.base.CommonAdapter;
import com.hthy.futures.base.CommonViewHolder;
import com.hthy.futures.bean.OrderTicket;
import com.hthy.futures.bean.TradeOderStr;
import com.hthy.futures.inter.PostNewOrderClickListener;
import com.hthy.futures.ui.BillPostDialog;
import com.hthy.futures.utils.AnimationLoader;
import com.hthy.futures.utils.Contant;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.StringUtils;
import com.hthy.futures.utils.ToastUtil;
import com.hthy.futures.view.EditTextWithDel;
import com.vilyever.socketclient.SocketClient;

import java.util.HashMap;

import static com.hthy.futures.utils.Contant.BILL_TAB_PENDING_ORDER;
import static com.hthy.futures.utils.Contant.BILL_TAB_POSITION;
import static com.hthy.futures.utils.Contant.TRADE_BUY;
import static com.hthy.futures.utils.Contant.TRADE_BUY_LIMIT;
import static com.hthy.futures.utils.Contant.TRADE_BUY_STOP;
import static com.hthy.futures.utils.Contant.TRADE_DATATYPE_LIMIT;
import static com.hthy.futures.utils.Contant.TRADE_DATATYPE_MARKET;
import static com.hthy.futures.utils.Contant.TRADE_DIRECTION_BUY;
import static com.hthy.futures.utils.Contant.TRADE_DIRECTION_SELL;
import static com.hthy.futures.utils.Contant.TRADE_SELL;
import static com.hthy.futures.utils.Contant.TRADE_SELL_LIMIT;
import static com.hthy.futures.utils.Contant.TRADE_SELL_STOP;
import static com.vilyever.resource.Resource.getColor;
import static com.vilyever.resource.Resource.getResources;
import static com.vilyever.resource.Resource.getString;

/**
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/21
 */

public class BillAdapter extends CommonAdapter<OrderTicket> {

    public SocketClient mSocketClient;
    private int mKeyFlag;
    private int op = -1;
    private int updatePosition;
    private boolean isFromBillPOST = false;
    private int isRemove;
    private double mYinkui;  // 更新的盈亏值
    private TextView mTipView;
    private double mOrder_s_spread;
    private String mChildORderType;
    private String mStr;
    private double newUiPrice;

    ListView listView;

    //记录当前展开项的索引
    private int expandPosition = -1;
    private HashMap<Integer, Boolean> toggleStateMap;

    public BillAdapter(Context context, ListView mListView, int layoutId, SocketClient socketClient) {
        super(context, layoutId);
        this.mSocketClient = socketClient;
        listView = mListView;
    }

    @Override
    public void convert(final CommonViewHolder vh, final OrderTicket item) {
        mTipView = (TextView) vh.getView(R.id.tv_tip);
        // 在挂单里面才有删除按钮
        if (BILL_TAB_POSITION == mKeyFlag) {
            vh.getView(R.id.bt_delete).setVisibility(View.GONE);
            vh.getView(R.id.bt_open_position).setVisibility(View.VISIBLE);

            //
            vh.getView(R.id.ll_hold).setVisibility(View.GONE);
            if (AppContext.isMarket) {
                vh.getView(R.id.ll_value).setVisibility(View.GONE);
                vh.getView(R.id.ll_tab1).setVisibility(View.GONE);
                vh.getView(R.id.bt_update).setVisibility(View.GONE);
            } else {
                vh.getView(R.id.ll_value).setVisibility(View.VISIBLE);
                vh.getView(R.id.ll_tab1).setVisibility(View.VISIBLE);
                vh.getView(R.id.bt_update).setVisibility(View.VISIBLE);
            }

            /*vh.getView(R.id.ll_value).setVisibility(View.GONE);
            vh.getView(R.id.ll_tab1).setVisibility(View.GONE);
            vh.getView(R.id.bt_update).setVisibility(View.GONE);*/

            // 提示区域的
            vh.getView(R.id.ll_hold_tip_view).setVisibility(View.GONE);
            vh.getView(R.id.ll_tab2).setVisibility(View.GONE);



            vh.setText(R.id.tv_holding_price, StringUtils.double_df.format(StringUtils.toDouble(item.getDbHoldPrice()))); //持 仓 价
            vh.setText(R.id.tv_stock_price, StringUtils.double_df.format(StringUtils.toDouble(item.getDbLastSwap())));  // 库存费
            vh.setText(R.id.tv_open_price, StringUtils.double_df.format(StringUtils.toDouble(item.getDbHoldPrice())));   // 开仓价

            // 根据正负来显示颜色
            double yinKui = item.yinKui;
            vh.setText(R.id.tv_profit, StringUtils.toDoubleStr(yinKui + ""));  // 盈     亏
            if (yinKui > 0) {
                ((TextView) vh.getView(R.id.tv_profit)).setTextColor(Color.RED);
            } else if (yinKui == 0) {
                ((TextView) vh.getView(R.id.tv_profit)).setTextColor(Color.GRAY);
            } else if (yinKui < 0) {
                ((TextView) vh.getView(R.id.tv_profit)).setTextColor(getColor(R.color.k_candle_common_color));
            }
        } else {
            vh.getView(R.id.bt_delete).setVisibility(View.VISIBLE);
            vh.getView(R.id.bt_open_position).setVisibility(View.GONE);

            vh.getView(R.id.ll_hold).setVisibility(View.VISIBLE);
            //vh.getView(R.id.ll_value).setVisibility(View.GONE);

            vh.getView(R.id.ll_hold_tip_view).setVisibility(View.VISIBLE);
            vh.getView(R.id.ll_tab1).setVisibility(View.GONE);
            vh.getView(R.id.ll_tab2).setVisibility(View.VISIBLE);

            vh.getView(R.id.bt_update).setVisibility(View.VISIBLE);
            // 最新价
            //double uiPrice = StringUtils.toDouble(item.uiPrice);
            double uiPrice = StringUtils.toDouble(item.uiPrice); // 代表最新价格
            if (uiPrice > 0) {
                ((TextView) vh.getView(R.id.tv_newPrice)).setTextColor(Color.RED);
            } else if (uiPrice == 0) {
                ((TextView) vh.getView(R.id.tv_newPrice)).setTextColor(Color.GRAY);
            } else if (uiPrice < 0) {
                ((TextView) vh.getView(R.id.tv_newPrice)).setTextColor(getColor(R.color.colorPrimary));
            }
            vh.setText(R.id.tv_newPrice, uiPrice + "");

            // 8102 挂单 (44是没有的）
            vh.setText(R.id.tv_bill_hold_price, StringUtils.double_df.format(StringUtils.toDouble(item.getDbOrderPrice())));

            // 挂单中的止盈价、止损价先隐藏
            vh.getView(R.id.ll_value).setVisibility(View.GONE);
            vh.getView(R.id.ll_tab2).setVisibility(View.GONE);
        }

        vh.setText(R.id.tv_trade_name, item.getSsProductCode());
        vh.setText(R.id.tv_trade_number, item.getUiOrderUid());  // 单      号

        vh.setText(R.id.tv_handle_num, StringUtils.double_df.format(StringUtils.toDouble(item.getDbOrderSize())));    // 手      数  跟14有区别没

        // 规定如果没有 止 盈 价  止 损 价 ，就直接空白
        // 还得通过计算他的百分比来是否显示
        // 止盈止损百分比计算过程           （在单据那边如果止损百分比>95%，也是不显示的）  TODO
        // 买 ：  止损价 = 当前价-（（保证金*止损百分比）/ 合约单位） ， 止盈价 = 当前价 +（（保证金*止盈百分比）/ 合约单位）
        // 卖的话：止损价 = 当前价+（（保证金*止损百分比）/ 合约单位）   止盈价 = 当前价 -（（保证金*止盈百分比）/ 合约单位）
        double zs = StringUtils.toDouble(item.get_$8025());  // 止 损 价
        if (zs > 0) {
            String item_$54 = item.getOrderDirectionValue(); // 先判断买卖方向
            double uiPrice = StringUtils.toDouble(item.uiPrice);  // 当前价
            double contractUnit = StringUtils.toDouble(item.contractUnit); // 合约单位
            double initGuaranteeMoney = StringUtils.toDouble(item.initGuaranteeMoney);// 初始保障金
            String moneyHoldType = item.moneyHoldType;   // 保证金类型
            double hand_sum = StringUtils.toDouble(item.getDbOrderSize());// 手数
            // 计算保证金-------
            double mAccupidMoney = 0;
            // 判断是保证金类型（包括比例与固定两种）
            if (moneyHoldType.equals("1")) {  // 比例
                // 占用保证金 = 商品信息->初始保证金 * 行情价 * 合约数量 * 单据数量
                mAccupidMoney = initGuaranteeMoney * uiPrice * contractUnit * hand_sum;
            } else if (moneyHoldType.equals("2")) {
                // 占用保证金 = 商品信息->初始保证金 * 单据数量
                mAccupidMoney = initGuaranteeMoney * hand_sum;
            }

            // 计算止损百分比     b 止损百分比 = （当前价-止损价）*合约单位/保证金    s 止损百分比 = （止损价-当前价）*合约单位/保证金
            double zsbfb = 0;
            if (item_$54.equals("b")) {
                zsbfb = (uiPrice-zs)*contractUnit/mAccupidMoney;
            } else {
                zsbfb = (zs - uiPrice)*contractUnit/mAccupidMoney;
            }
            if (zsbfb > 0.95) {
                item.setDbSlPrice("");
            }
        }
        vh.setText(R.id.tv_stop_profit, 0 == StringUtils.toDouble(item.getDbTpPrice()) ? "" : StringUtils.double_df.format(StringUtils.toDouble(item.getDbTpPrice())));  // 止 盈 价
        vh.setText(R.id.tv_stop_outprice, 0 == StringUtils.toDouble(item.get_$8025()) ? "":StringUtils.double_df.format(StringUtils.toDouble(item.get_$8025())));  // 止 损 价
        vh.setText(R.id.tv_time, BILL_TAB_POSITION == mKeyFlag ? item.getSsExecuteTime():item.getOrderTime());  // 时间

        TextWatcher watcher = new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Double price = StringUtils.toDouble(s.toString());
                if (price <= 0) {
                    return;
                }
                double v_add = price + mOrder_s_spread;
                double v_less = price - mOrder_s_spread;
                if (TRADE_BUY_LIMIT.equals(mChildORderType)) {
                    mStr = "止盈>=" + v_add + "止损<=" + v_less;
                    vh.setText(R.id.tv_tip_tab2_yin, "止盈>=" + v_add);
                    vh.setText(R.id.tv_tip_tab2_sun, "止损<=" + v_less);
                } else if (TRADE_SELL_LIMIT.equals(mChildORderType)) {
                    mStr = "止盈<=" + v_less + "止损>=" + v_add;
                    vh.setText(R.id.tv_tip_tab2_yin, "止盈<=" + v_less);
                    vh.setText(R.id.tv_tip_tab2_sun, "止损>=" + v_add);
                } else if (TRADE_BUY_STOP.equals(mChildORderType)) {
                    mStr = "止盈>=" + v_add + "止损<=" + v_less;
                    vh.setText(R.id.tv_tip_tab2_yin, "止盈>=" + v_add);
                    vh.setText(R.id.tv_tip_tab2_sun, "止损<=" + v_less);
                } else if (TRADE_SELL_STOP.equals(mChildORderType)) {
                    mStr = "止盈<=" + v_less + "止损>=" + v_add;
                    vh.setText(R.id.tv_tip_tab2_yin, "止盈<=" + v_less);
                    vh.setText(R.id.tv_tip_tab2_sun, "止损>=" + v_add);
                }
                vh.setText(R.id.tv_tip_money, mStr);
            }
        };
        ((EditTextWithDel) vh.getView(R.id.et_hold_price)).addTextChangedListener(watcher);

        // 8028 子订单类型 1 - buy , 2 - sell , 3 - buy limit 4 - buy stop 5 - sell limit 6 - sell stop
        final String item_$8028 = item.getLimitOrderType();
        int orderType = Integer.parseInt(item_$8028);
        switch (orderType) {
            case 1:
                vh.setText(R.id.tv_trade_diration,  getResources().getString(R.string.buy));
                vh.getView(R.id.tv_trade_diration).setBackground(getResources().getDrawable(R.drawable.round_red));
                break;
            case 2:
                vh.setText(R.id.tv_trade_diration,  getResources().getString(R.string.sell));
                vh.getView(R.id.tv_trade_diration).setBackground(getResources().getDrawable(R.drawable.round_blue));
                break;
            case 3:
                vh.setText(R.id.tv_trade_diration,  getResources().getString(R.string.buy));
                vh.getView(R.id.tv_trade_diration).setBackground(getResources().getDrawable(R.drawable.round_red));

                if (BILL_TAB_POSITION != mKeyFlag) {
                    vh.setText(R.id.tv_order_type, getString(R.string.pending_type_buylimit));
                }
                break;
            case 4:
                vh.setText(R.id.tv_trade_diration,  getResources().getString(R.string.buy));
                vh.getView(R.id.tv_trade_diration).setBackground(getResources().getDrawable(R.drawable.round_red));
                if (BILL_TAB_POSITION != mKeyFlag) {
                    vh.setText(R.id.tv_order_type, getString(R.string.pending_type_buystop));
                }
                break;
            case 5:
                vh.setText(R.id.tv_trade_diration,  getResources().getString(R.string.sell));
                vh.getView(R.id.tv_trade_diration).setBackground(getResources().getDrawable(R.drawable.round_blue));
                if (BILL_TAB_POSITION != mKeyFlag) {
                    vh.setText(R.id.tv_order_type, getString(R.string.pending_type_selllimit));
                }
                break;
            case 6:
                vh.setText(R.id.tv_trade_diration,  getResources().getString(R.string.sell));
                vh.getView(R.id.tv_trade_diration).setBackground(getResources().getDrawable(R.drawable.round_blue));
                if (BILL_TAB_POSITION != mKeyFlag) {
                    vh.setText(R.id.tv_order_type, getString(R.string.pending_type_sellstop));
                }
                break;
        }


        final int position = getDatas().indexOf(item);


        final View hiddenView = vh.getView(R.id.hidden_view);

        //如果点击的是当前项，则将其展开，否则将其隐藏
       if (toggleStateMap != null) {
            if (toggleStateMap.get(position).equals(true)) {
               // AnimationLoader.magiceShow3(mContext, hiddenView);
                hiddenView.setVisibility(View.VISIBLE);
            } else {
                hiddenView.setVisibility(View.GONE);
                //AnimationLoader.magiceShow3(mContext, hiddenView);
            }
        }

        vh.getView(R.id.list_item).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleStateMap.put(expandPosition, false);  // 要把历史的位置置为false
                if(expandPosition == position){
                    expandPosition = -1;
                    toggleStateMap.put(position, false);
                }else{
                    expandPosition = position;
                    toggleStateMap.put(position, true);
                }
                notifyDataSetChanged();
                listView.smoothScrollToPosition(position);
            }
        });

        //计算 止盈价  止损价
        calucuteProfit(vh, item);


        ((RadioGroup) vh.getView(R.id.group)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.bt_update:       // 修改
                        op = Contant.BILL_OP_UPDATE;
                        postRequest(vh, item, position);
                        ((RadioButton)vh.getView(R.id.bt_update)).setChecked(false);
                        break;
                    case R.id.bt_open_position:     // 平仓
                        op = Contant.BILL_OP_CLOSE;
                        postRequest(vh, item, position);
                        ((RadioButton)vh.getView(R.id.bt_open_position)).setChecked(false);
                        break;
                    case R.id.bt_delete:     // 删除
                        op = Contant.BILL_OP_DELETE;
                        postRequest(vh, item, position);
                        ((RadioButton)vh.getView(R.id.bt_delete)).setChecked(false);
                        break;
                }
            }
        });

        vh.getView(R.id.ll_drop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 关闭动画 (用这个动画关闭后）就再也打不开，不知道啥原因
                //AnimationLoader.animateClose(hiddenView);
            }
        });

        /*提交，取消按钮隐藏，所以下面两个逻辑也没用了*/
        // 提交
        vh.getView(R.id.bt_post).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postRequest(vh, item, position);
            }
        });
        // 取消
        vh.getView(R.id.bt_dismiss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 关闭动画
                AnimationLoader.animateClose(hiddenView);
            }
        });

        vh.getView(R.id.btn_hold_sub).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditTextWithDel editTextWithDel = (EditTextWithDel) vh.getView(R.id.et_hold_price);
                String holdPrice = editTextWithDel.getText().toString().trim();
                double comprice = 0;
                if (holdPrice != null && !"".equals(holdPrice)) {
                    comprice = StringUtils.toDouble(holdPrice);
                }
                if (comprice > 1) {
                    comprice--;
                    editTextWithDel.setText(comprice + "");
                } else {
                    ToastUtil.show(R.string.sub_tip);
                }
            }
        });
        vh.getView(R.id.btn_hold_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditTextWithDel editTextWithDel = (EditTextWithDel) vh.getView(R.id.et_hold_price);
                String holdPrice = editTextWithDel.getText().toString().trim();
                double comprice = 0;
                if (holdPrice != null && !"".equals(holdPrice)) {
                    comprice = StringUtils.toDouble(holdPrice);
                }
                comprice++;
                editTextWithDel.setText(comprice + "");
            }
        });
    }

    /**
     * 提交逻辑
     * @param vh
     * @param item
     * @param position
     */
    private void postRequest(CommonViewHolder vh, OrderTicket item, final int position) {
        String holdPrice = ((EditTextWithDel) vh.getView(R.id.et_hold_price)).getText().toString().trim();
        String stopSurPlusPrice = ((EditTextWithDel) vh.getView(R.id.stop_surplus)).getText().toString().trim();
        String stopLossPrice = ((EditTextWithDel) vh.getView(R.id.et_stop_loss)).getText().toString().trim();


        if (op == -1) {
            Toast.makeText(mContext, "请选择操作类型", Toast.LENGTH_SHORT).show();
            return;
        }
        //
        if ((BILL_TAB_POSITION == mKeyFlag) && (op == Contant.BILL_OP_UPDATE)) {
            // 其中两个值都是空的话要提示
        }

        final TradeOderStr tradeOderStr = new TradeOderStr();
        tradeOderStr.tradeCode = item.getSsProductCode();
        tradeOderStr.tradeNum = item.getUiOrderUid();
        tradeOderStr.tradeBuyCount = item.getDbOrderSize();
        tradeOderStr.trade_operation_type = "1";
        tradeOderStr.trade_commision_price = holdPrice;  // 挂单价格
        if (!StringUtils.isEmpty(stopSurPlusPrice)) {
            tradeOderStr.trade_dicount_price = stopSurPlusPrice; // 止盈
        }
        if (!StringUtils.isEmpty(stopLossPrice)) {
            tradeOderStr.trade_stop_price = stopLossPrice;  // 止损
        }

        String direction = item.getLimitOrderType();
        if (TRADE_BUY.equals(direction) || TRADE_BUY_LIMIT.equals(direction) || TRADE_BUY_STOP.equals(direction)) {
            tradeOderStr.trade_direction = TRADE_DIRECTION_BUY;
        } else {
            tradeOderStr.trade_direction = TRADE_DIRECTION_SELL;
        }

        tradeOderStr.trade_type = item.getLimitOrderType();

        String dialogTip = null;
        if (op == Contant.BILL_OP_UPDATE) {
            tradeOderStr.tradeOC = Contant.TRADE_NEW;  // 1’ - 建仓‘2’ - 平仓是他
            tradeOderStr.tradeFlag = Contant.TRADE_FLAG_UPDATE_VALUE;

            isRemove = Contant.BILL_OP_UPDATE;
            // 更新数据源 ---当然外面还得刷新下adapter
            if (!StringUtils.isEmpty(stopSurPlusPrice)) {
                item.setDbTpPrice(stopSurPlusPrice);
            }
            if (!StringUtils.isEmpty(stopLossPrice)) {
                item.setDbSlPrice(stopLossPrice);
            }
            if (!StringUtils.isEmpty(holdPrice)) {
                //item.set 这里面界面应该要显示
                item.setDbOrderPrice(holdPrice);
            }
            //dialogTip = "止盈价：" + stopSurPlusPrice + " 止损价：" + stopLossPrice + ",确认修改？";
            dialogTip = "确认修改？";

        } else if (op == Contant.BILL_OP_CLOSE) {  // 平仓
            tradeOderStr.tradeOC = Contant.TRADE_CLOSE;
            tradeOderStr.tradeFlag = Contant.TRADE_FLAG_NEW;

            isRemove = Contant.BILL_OP_CLOSE;
            dialogTip = "确定"+getString(R.string.pincan)+"?";
        } else if (op == Contant.BILL_OP_DELETE) {  // 刪除
            tradeOderStr.tradeOC = Contant.TRADE_NEW;
            tradeOderStr.tradeFlag = Contant.TRADE_FLAG_REVOKE; //‘1’-  新建单‘2’ - 修改限价单‘3’ -（修改止损，获利价）‘4’ - 撤销单
            isRemove = Contant.BILL_OP_DELETE;
            dialogTip = "确定删除？";
        }
        // 如果是挂单，并且是做修改操作
        if (op == Contant.BILL_OP_UPDATE && mKeyFlag == BILL_TAB_PENDING_ORDER) {
            tradeOderStr.tradeFlag = Contant.TRADE_FLAG_UPDATE;
           // dialogTip = "挂单价:" + holdPrice + "止盈价：" + stopSurPlusPrice + " 止损价：" + stopLossPrice + ",确认修改？";
            dialogTip = "确认修改？";
        }

        // 分别提示 修改平仓之间的信息

        /*AlertDialog.Builder dialog = DialogHelp.getConfirmDialog(mContext, dialogTip, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (mKeyFlag == BILL_TAB_POSITION) {
                    mSocketClient.sendString(ST_TradeApi.trade(true, "1011", tradeOderStr));
                } else if (mKeyFlag == BILL_TAB_PENDING_ORDER) {
                    mSocketClient.sendString(ST_TradeApi.trade(false, "1011", tradeOderStr));
                }
                // 把要操作的位置传递到外面
                updatePosition = position;
                isFromBillPOST = true;
            }
        });
        dialog.show();*/

        if (BILL_TAB_POSITION == mKeyFlag) {
            tradeOderStr.trade_data_type = TRADE_DATATYPE_MARKET;
        } else {
            tradeOderStr.trade_data_type = TRADE_DATATYPE_LIMIT;
        }


        BillPostDialog billPostDialog = new BillPostDialog(mContext);
        billPostDialog.setPostNewOrderClickListner(new PostNewOrderClickListener() {
            @Override
            public void post() {
                if (mKeyFlag == BILL_TAB_POSITION) {
                    mSocketClient.sendData(ST_TradeApi.trade(true, "1011", tradeOderStr));
                } else if (mKeyFlag == BILL_TAB_PENDING_ORDER) {
                    mSocketClient.sendData(ST_TradeApi.trade(false, "1011", tradeOderStr));
                }
                // 把要操作的位置传递到外面
                updatePosition = position;
                isFromBillPOST = true;
                toggleStateMap.put(position, false);  // 不加的话，外面还是张开的
            }
        });
        billPostDialog.setCancelable(false);
        billPostDialog.setCanceledOnTouchOutside(true);
        billPostDialog.setMessTip(dialogTip);
        billPostDialog.show();
    }

    /**
     * 计算 止盈价  止损价
     *
     * @param vh
     * @param item
     */
    private void calucuteProfit(CommonViewHolder vh, OrderTicket item) {

        // 计算止盈价和止损价相关关系
        /*市场价
                     卖   止损价>= 行情价+30（点差）          止盈价<=行情价-30
                     买   止损价>= 行情价-30（点差）          止盈价<=行情价+30
                     */
        Double itemPrice;

        double quote_buy_spread = Double.parseDouble(item.buyPriceSpreed); //8077 报价买价点差   比如10
        double quote_sell_spread = Double.parseDouble(item.sellPriceSpreed); // 8078 报价卖价点差

        if (item.uiPrice != null) {
            itemPrice = Double.parseDouble(item.uiPrice) + quote_buy_spread;  // 这个是否会变 TODO
        } else {
            itemPrice = Double.parseDouble(item.getDbOrderPrice());
        }

        // 8129 止损下单点差  比如30
        mOrder_s_spread = Double.parseDouble(item.order_s_spread);
        double order_y_spread = Double.parseDouble(item.order_y_spread);  // 8130 止盈下单点差

        String buy_y = StringUtils.double_df.format(itemPrice + mOrder_s_spread);
        String buy_s = StringUtils.double_df.format(itemPrice - order_y_spread);

        String sell_y = StringUtils.double_df.format(itemPrice + order_y_spread);
        String sell_s = StringUtils.double_df.format(itemPrice - mOrder_s_spread);

        // 计算挂单中的价位
        String gua_add = StringUtils.double_df.format(itemPrice + 50);
        String gua_jian = StringUtils.double_df.format(itemPrice - 50);

        LogUtils.e("BillAdapter", "gua_add" + gua_add + "^^^^^" + "gua_jian" + gua_jian);
        mChildORderType = item.getLimitOrderType();
        if (TRADE_BUY.equals(mChildORderType)) {
            mTipView.setText("止盈价>=" + buy_y + "止损价<=" + buy_s);
            vh.setText(R.id.tv_tip_tab1_yin, "止盈价>=" + buy_y);
            vh.setText(R.id.tv_tip_tab1_sun, "止损价<=" + buy_s);
        } else if (TRADE_SELL.equals(mChildORderType)) {
            mTipView.setText("止盈价<=" + sell_s + "止损价>=" + sell_y);
            vh.setText(R.id.tv_tip_tab1_yin, "止盈价<=" + sell_s);
            vh.setText(R.id.tv_tip_tab1_sun, "止损价>=" + sell_y);
        } else if (TRADE_BUY_LIMIT.equals(mChildORderType)) {
            mTipView.setText("价位<=" + gua_jian);
            vh.setText(R.id.reference_margin, "价位<=" + gua_jian);
        } else if (TRADE_BUY_STOP.equals(mChildORderType)) {
            mTipView.setText("价位>=" + gua_add);
            vh.setText(R.id.reference_margin, "价位>=" + gua_add);
        } else if (TRADE_SELL_LIMIT.equals(mChildORderType)) {
            mTipView.setText("价位>=" + gua_add);
            vh.setText(R.id.reference_margin, "价位>=" + gua_add);
        } else if (TRADE_SELL_STOP.equals(mChildORderType)) {
            mTipView.setText("价位<=" + gua_jian);
            vh.setText(R.id.reference_margin, "价位<=" + gua_jian);
        }
    }


    public void setKeyFlag(int keyFrg) {
        this.mKeyFlag = keyFrg;
    }

    // 把要操作的位置传递到外面
    public int getUpdatePosition() {
        return updatePosition;
    }

    // 是否操作來自於bill ,因爲新订单那边响应的也是1012内容
    public boolean isFromBillPOST() {
        return isFromBillPOST;
    }

    public void setFromBillPost(boolean b) {
        this.isFromBillPOST = b;
    }

    // 如果是删除或是平仓操作
    public int isNeedRemove() {
        return isRemove;
    }

    public void setToogleStateMap(HashMap<Integer, Boolean> toggleStateMap) {
        this.toggleStateMap = toggleStateMap;
    }
}
